package org.wejob.web;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.*;
import java.util.function.Consumer;

public class WebUtil {
    //因为这里只需要一个server，可以考虑作为静态变量，但是如果这里只是提供基本方法逻辑的话考虑只封装代码
    private static Selector selector;



    public static Selector getSelector(Selector selector) {
        if(selector.isOpen())
            return selector;
        try {
            selector=Selector.open();
        } catch (IOException e) {
            if(selector.isOpen())
                return selector;
        }
        return selector;
    }

    public ServerSocketChannel initServer(ServerSocketChannel server,int port,Selector selector) throws IOException {
        //通过open方法来打开一个未绑定的ServerSocketChannel实例
        InetSocketAddress isa = new InetSocketAddress(port);
        //将该ServerSocketChannel绑定到指定IP地址
        server.socket().bind(isa);
        //设置ServerSocket以非阻塞方式工作
        server.configureBlocking(false);
        //将Server注册到指定Selector对象
        server.register(selector, SelectionKey.OP_ACCEPT);
        return server;
    }

    public void startSelector(Selector selector, Consumer<SelectionKey>consumer) throws IOException {
        while(selector.select() > 0)
        {
            System.out.println("selector >0");
            //依次处理Selector上的每个已选择的SelectionKey
            for(SelectionKey sk : selector.selectedKeys())
            {
                //从selector上的已选择Key集中删除正在处理的SelectionKey
                selector.selectedKeys().remove(sk);
                //如果sk对应的通道包含客户端的连接请求
                consumer.accept(sk);
            }
        }
    }

}
